// utils/common.js - 通用工具函数

// 格式化时间
export const formatTime = (timestamp, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!timestamp) return '';
  
  // 如果没有引入dayjs，可以使用简单的日期格式化
  const date = new Date(timestamp);
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds);
};

// 格式化时间差（相对时间）
export const formatRelativeTime = (timestamp) => {
  if (!timestamp) return '';
  
  const now = Date.now();
  const diff = now - timestamp;
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }
  
  // 小于24小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }
  
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }
  
  // 大于30天，显示具体日期
  return formatTime(timestamp, 'YYYY-MM-DD');
};

// 格式化数字（添加千分位）
export const formatNumber = (num) => {
  if (num === null || num === undefined) return '0';
  
  return Number(num).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 格式化积分显示
export const formatPoints = (points) => {
  return formatNumber(points) + ' 积分';
};

// 防抖函数
export const debounce = (func, wait = 300) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 节流函数
export const throttle = (func, limit = 300) => {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};

// 深拷贝
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj.getTime());
  if (obj instanceof Array) return obj.map(item => deepClone(item));
  
  const clonedObj = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clonedObj[key] = deepClone(obj[key]);
    }
  }
  return clonedObj;
};

// 验证手机号
export const validatePhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

// 验证邮箱
export const validateEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 获取文件扩展名
export const getFileExtension = (filename) => {
  if (!filename) return '';
  const lastDotIndex = filename.lastIndexOf('.');
  if (lastDotIndex === -1) return '';
  return filename.slice(lastDotIndex + 1).toLowerCase();
};

// 验证图片文件
export const isValidImage = (filename) => {
  const validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  const extension = getFileExtension(filename);
  return validExtensions.includes(extension);
};

// 获取文件大小显示文本
export const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 生成随机字符串
export const generateRandomString = (length = 16) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

// 存储数组去重
export const uniqueArray = (arr, key) => {
  if (!Array.isArray(arr)) return [];
  
  if (key) {
    // 根据key去重
    const map = new Map();
    return arr.filter(item => !map.has(item[key]) && map.set(item[key], 1));
  } else {
    // 简单数组去重
    return [...new Set(arr)];
  }
};

// 判断是否为空对象
export const isEmptyObject = (obj) => {
  return obj && typeof obj === 'object' && Object.keys(obj).length === 0;
};

// 延迟函数
export const delay = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

// 获取任务状态文本
export const getTaskStatusText = (status) => {
  const statusMap = {
    'pending': '待领取',
    'ongoing': '进行中',
    'pending_review': '待审核',
    'completed': '已完成',
    'rejected': '已拒绝',
    'expired': '已过期',
    'canceled': '已取消'
  };
  return statusMap[status] || status;
};

// 获取任务状态颜色
export const getTaskStatusColor = (status) => {
  const colorMap = {
    'pending': '#409eff',
    'ongoing': '#e6a23c',
    'pending_review': '#67c23a',
    'completed': '#67c23a',
    'rejected': '#f56c6c',
    'expired': '#909399',
    'canceled': '#909399'
  };
  return colorMap[status] || '#909399';
};

// 检查是否有权限
export const checkPermission = (requiredPermission, userPermissions = []) => {
  if (!requiredPermission) return true;
  if (!Array.isArray(userPermissions)) return false;
  
  // 超级管理员权限
  if (userPermissions.includes('admin')) return true;
  
  // 检查是否包含所需权限
  return userPermissions.includes(requiredPermission);
};

// 处理错误信息
export const handleError = (error, showToast = true) => {
  console.error('Error:', error);
  
  let errorMessage = '操作失败，请稍后重试';
  
  if (error.response) {
    // 服务器返回错误
    errorMessage = error.response.data?.msg || errorMessage;
  } else if (error.message) {
    // 其他错误信息
    errorMessage = error.message;
  }
  
  if (showToast) {
    uni.showToast({
      title: errorMessage,
      icon: 'none'
    });
  }
  
  return errorMessage;
};

// 获取设备信息
export const getDeviceInfo = () => {
  try {
    return uni.getSystemInfoSync();
  } catch (error) {
    console.error('获取设备信息失败:', error);
    return {};
  }
};

// 判断是否为iOS设备
export const isIOS = () => {
  const systemInfo = getDeviceInfo();
  return systemInfo.platform === 'ios';
};

// 判断是否为Android设备
export const isAndroid = () => {
  const systemInfo = getDeviceInfo();
  return systemInfo.platform === 'android';
};